import { ElMessage } from "element-plus";
import router from "./router";
import { useUserStore } from "./stores/user";
import { getProfileAPI } from "./apis/user";
import type { RouteRecordRaw } from "vue-router";
import { asyncRoutes } from "./router/asyncRoutes";
import { useMenuStore } from "./stores/menu";

const WHITE_LIST = ["/login", "/404"];

const getFirstRoutePerms = (permissions: string[])=>{
const tempArr = permissions.map((item)=>item.split(":")[0])
// 数组去重
return Array.from(new Set(tempArr))
}

// 处理二级路由权限数据
const getSecondRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return Array.from(new Set(newArr))
}

// 根据权限筛选出匹配的路由
const getRoutes = (
  firstRoutePerms: string[],  // 一级路由权限集合
  secondRoutePerms: string[], // 二级路由权限集合
  asyncRoutes: RouteRecordRaw[] // 所有的动态路由数据
)=>{
  console.log(firstRoutePerms,secondRoutePerms,asyncRoutes)
    // 超级管理员，不做筛选，返回所有路由信息
    if(firstRoutePerms.includes('*')){
      return [...asyncRoutes]
    }
  // 过滤出一级路由
  const firstRoutes = asyncRoutes.filter(route =>{
    return firstRoutePerms.includes(route.meta!.permission!)
  })
  // 基于筛选的一级路由，继续筛选二级路由
  const lastRoutes = firstRoutes.map(route => {
    return {
      ...route,
      // 筛选二级路由
      children: route.children?.filter(v=> secondRoutePerms.includes(v.meta!.permission!))
    }
  })
  return lastRoutes
}

// 路由导航守卫
router.beforeEach(async (to, from, next) => {
// 获取token
const store = useUserStore();
if(store.token){
  
// 如果没有用户信息，发送请求获取，并保存到 store 中
if(!store.profile.id){
  const res = await getProfileAPI()
  store.setProfile(res.data)  
  console.log('profile res', res);
  const menus = getFirstRoutePerms(res.data.permissions)
  const smenus = getSecondRoutePerms(res.data.permissions)
      // console.log('menus', menus);
      // console.log('smenus', smenus);
      // 1.获取匹配的路由
      const perRoutes = getRoutes(menus, smenus, asyncRoutes)
      // console.log('lastRoutes', perRoutes);
      // 2.动态路由表加入到路由系统中(当浏览器中访问路由的路径 显示渲染出来对应的组件)
      perRoutes.forEach(route =>{
        router.addRoute(route as RouteRecordRaw)
      })
      // 3.保存侧栏菜单路由
      const menuStore = useMenuStore()
      menuStore.setMenuList(perRoutes as RouteRecordRaw[])
      next({...to})
}else{
  // 有token，放行
  next()
}

}else if(WHITE_LIST.includes(to.path)){
// 在白名单中，在放行
next()
}else{
  // 不是以上两种情况，跳转到登录页
  next("/login")
  ElMessage.warning("登录信息无效，请先登录")
}


});
